package com.person.mengshuai.mytestdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.person.mengshuai.mytestdemo.domain.response.Result;
import com.person.mengshuai.mytestdemo.entity.BUserRole;
import com.person.mengshuai.mytestdemo.mapper.BUserRoleMapper;
import com.person.mengshuai.mytestdemo.service.BUserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统管理 - 用户角色关联表  服务实现类
 * </p>
 *
 * @author ms
 * @since 2024-08-02
 */
@Service
public class BUserRoleImpl extends ServiceImpl<BUserRoleMapper, BUserRole> implements BUserRoleService {

    @Override
    public Result insertUserRole(String userId, List<Integer> roleIds) {
        List<BUserRole> bUserRoles = findUserRoleByUserId(userId);
        // 删除已有全部角色
        if (!CollectionUtils.isEmpty(bUserRoles)) {
            baseMapper.deleteBatchIds(bUserRoles.stream().map(BUserRole::getId).collect(Collectors.toList()));
        }
        List<BUserRole> userRoles = new ArrayList<>();
        for (int roleId : roleIds) {
            BUserRole bUserRole = new BUserRole();
            bUserRole.setUserId(userId);
            bUserRole.setRoleId(roleId);
            userRoles.add(bUserRole);
        }
        // 批量插入用户新角色
        return Result.success(this.saveBatch(userRoles));
    }

    @Override
    public List<BUserRole> findUserRoleByUserId(String userId) {
        QueryWrapper<BUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BUserRole::getUserId, userId);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public int deleteUserRoleByUserId(String userId) {
        QueryWrapper<BUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BUserRole::getUserId, userId);
        return baseMapper.delete(queryWrapper);
    }

    @Override
    public List<BUserRole> findUserRoleByRoleId(int roleId) {
        QueryWrapper<BUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BUserRole::getRoleId, roleId);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public int deleteUserRoleByRoleId(int roleId) {
        QueryWrapper<BUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BUserRole::getRoleId, roleId);
        return baseMapper.delete(queryWrapper);
    }
}
